package com.aimosheng.main.activity;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aimosheng.common.CommonAppConfig;
import com.aimosheng.common.CommonAppContext;
import com.aimosheng.common.Constants;
import com.aimosheng.common.HtmlConfig;
import com.aimosheng.common.activity.AbsActivity;
import com.aimosheng.common.activity.WebViewActivity;
import com.aimosheng.common.bean.UserBean;
import com.aimosheng.common.event.LoginSuccessEvent;
import com.aimosheng.common.glide.ImgLoader;
import com.aimosheng.common.http.CommonHttpConsts;
import com.aimosheng.common.http.CommonHttpUtil;
import com.aimosheng.common.http.HttpCallback;
import com.aimosheng.common.interfaces.CommonCallback;
import com.aimosheng.common.interfaces.OnItemClickListener;
import com.aimosheng.common.mob.LoginData;
import com.aimosheng.common.mob.MobBean;
import com.aimosheng.common.mob.MobCallback;
import com.aimosheng.common.mob.MobLoginUtil;
import com.aimosheng.common.utils.DialogUitl;
import com.aimosheng.common.utils.SpUtil;
import com.aimosheng.common.utils.ToastUtil;
import com.aimosheng.main.R;
import com.aimosheng.main.adapter.LoginTypeAdapter;
import com.aimosheng.main.dialog.LoginTipDialogFragment;
import com.aimosheng.main.http.MainHttpConsts;
import com.aimosheng.main.http.MainHttpUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;


/**
 * Created by cxf on 2018/9/17.
 */

public class LoginActivity extends AbsActivity implements OnItemClickListener<MobBean> {

    private View mRoot;
    private ImageView mBg;
    private RecyclerView mRecyclerView;
    private ObjectAnimator mAnimator;
    private MobLoginUtil mLoginUtil;
    private boolean mFirstLogin;//是否是第一次登录
    private boolean mIsShowRecommend;
    private String mLoginType = Constants.MOB_PHONE;//登录方式

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected boolean isStatusBarWhite() {
        return true;
    }

    @Override
    protected void main() {
        mRoot = findViewById(R.id.root);
        ImageView appIcon = findViewById(R.id.app_icon);
        ImgLoader.display(mContext, CommonAppConfig.getInstance().getAppIconRes(), appIcon);
        mBg = findViewById(R.id.bg);
        mBg.post(new Runnable() {
            @Override
            public void run() {
                if (mBg != null && mRoot != null) {
                    int bgHeight = mBg.getHeight();
                    int rootHeight = mRoot.getHeight();
                    int dy = bgHeight - rootHeight;
                    if (dy > 0) {
                        mAnimator = ObjectAnimator.ofFloat(mBg, "translationY", 0, -dy);
                        mAnimator.setInterpolator(new LinearInterpolator());
                        mAnimator.setDuration(4000);
                        mAnimator.setRepeatCount(-1);
                        mAnimator.setRepeatMode(ValueAnimator.REVERSE);
                        mAnimator.start();
                    }
                }
            }
        });

        EventBus.getDefault().register(this);
        MainHttpUtil.getLoginInfo(new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                if (code == 0 && info.length > 0) {
                    JSONObject obj = JSON.parseObject(info[0]);
                    String[] loginTypeArray = JSON.parseObject(obj.getString("login_type"), String[].class);
                    List<MobBean> list = MobBean.getLoginTypeList(loginTypeArray);
                    if (list != null && list.size() > 0) {
                        mRecyclerView = findViewById(R.id.recyclerView);
                        mRecyclerView.setHasFixedSize(true);
                        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
                        LoginTypeAdapter adapter = new LoginTypeAdapter(mContext, list);
                        adapter.setOnItemClickListener(LoginActivity.this);
                        mRecyclerView.setAdapter(adapter);
                        mLoginUtil = new MobLoginUtil();
                    }
                    TextView loginTipTextView = findViewById(R.id.tip);
                    if (loginTipTextView != null) {
                        JSONObject loginInfo = obj.getJSONObject("login_alert");
                        String loginTip = loginInfo.getString("login_title");
                        if (TextUtils.isEmpty(loginTip)) {
                            return;
                        }
                        SpannableString spannableString = new SpannableString(loginTip);
                        JSONArray msgArray = JSON.parseArray(loginInfo.getString("message"));
                        for (int i = 0, size = msgArray.size(); i < size; i++) {
                            final JSONObject msgItem = msgArray.getJSONObject(i);
                            String title = msgItem.getString("title");
                            int startIndex = loginTip.indexOf(title);
                            if (startIndex >= 0) {
                                ClickableSpan clickableSpan = new ClickableSpan() {

                                    @Override
                                    public void updateDrawState(TextPaint ds) {
                                        super.updateDrawState(ds);
                                        ds.setColor(0xff3399ee);
                                        ds.setUnderlineText(false);
                                    }

                                    @Override
                                    public void onClick(View widget) {
                                        WebViewActivity.forward(mContext, msgItem.getString("url"), false);
                                    }
                                };
                                int endIndex = startIndex + title.length();
                                spannableString.setSpan(clickableSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                            }
                        }
                        loginTipTextView.setText(spannableString);
                        loginTipTextView.setMovementMethod(LinkMovementMethod.getInstance());//不设置 没有点击事件
                        loginTipTextView.setHighlightColor(Color.TRANSPARENT); //设置点击后的颜色为透明
                    }

                    LoginTipDialogFragment fragment = new LoginTipDialogFragment();
                    fragment.setJSONObject(obj);
                    fragment.show(getSupportFragmentManager(), "LoginTipDialogFragment");
                }
            }
        });

    }


    public static void forward() {
        Intent intent = new Intent(CommonAppContext.sInstance, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        CommonAppContext.sInstance.startActivity(intent);
    }


//    public void loginClick(View v) {
//        int i = v.getId();
//        if (i == R.id.btn_tip) {
//            forwardTip();
//        }
//    }


    //登录即代表同意服务和隐私条款
    private void forwardTip() {
        WebViewActivity.forward(mContext, HtmlConfig.LOGIN_PRIVCAY);
    }

    private LoginData data;
    /**
     * 三方登录
     */
    private void loginBuyThird(LoginData data) {
        mLoginType = data.getType();
        this.data = data;
        MainHttpUtil.loginByThird(data.getOpenID(), data.getNickName(), data.getAvatar(), data.getFlag(), new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                onLoginSuccess(code, msg, info);
            }
        });
    }

    /**
     * 登录成功！
     */
    private void onLoginSuccess(int code, String msg, String[] info) {
        if (code == 0 && info.length > 0) {
            JSONObject obj = JSON.parseObject(info[0]);
            boolean isBindPhone = obj.getIntValue("isBindPhone") == 1;
//            boolean isBindPhone = false;
            if(isBindPhone){
                String uid = obj.getString("id");
                String token = obj.getString("token");
                mFirstLogin = obj.getIntValue("isreg") == 1;
                mIsShowRecommend = obj.getIntValue("issexrecommend") == 1;
                if (mIsShowRecommend) {
                    CommonAppConfig.getInstance().setLoginInfo(uid, token, false);
                } else {
                    CommonAppConfig.getInstance().setLoginInfo(uid, token, true);
                }
                SpUtil.getInstance().setStringValue(SpUtil.TX_IM_USER_SIGN, obj.getString("usersig"));
                //友盟统计登录
//            MobclickAgent.onProfileSignIn(mLoginType, uid);
                getBaseUserInfo();
            }else{
                LoginPhoneActivity.forward(mContext,this.data);
            }
        } else {
            ToastUtil.show(msg);
        }
    }

    /**
     * 获取用户信息
     */
    private void getBaseUserInfo() {
        MainHttpUtil.getBaseInfo(new CommonCallback<UserBean>() {
            @Override
            public void callback(UserBean bean) {
                if (mIsShowRecommend) {
                    SetProfileActivity.forward(mContext, bean, true);
                } else {
                    MainActivity.forward(mContext, mFirstLogin, false);
                    EventBus.getDefault().post(new LoginSuccessEvent());
                }
            }
        });
        ToastUtil.show(com.aimosheng.common.R.string.login_auth_success);
    }


    @Override
    public void onItemClick(MobBean bean, int position) {
        if (Constants.MOB_PHONE.equals(bean.getType())) {
            LoginPhoneActivity.forward(mContext);
            return;
        }
        if (mLoginUtil == null) {
            return;
        }
        final Dialog dialog = DialogUitl.loginAuthDialog(mContext);
        dialog.show();
        mLoginUtil.execute(bean.getType(), new MobCallback() {
            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    loginBuyThird((LoginData) data);
                }
            }

            @Override
            public void onError() {

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onFinish() {
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginSuccessEvent(LoginSuccessEvent e) {
        finish();
    }

    @Override
    protected void onDestroy() {
        if (mAnimator != null) {
            mAnimator.cancel();
        }
        mAnimator = null;
        EventBus.getDefault().unregister(this);
        CommonHttpUtil.cancel(CommonHttpConsts.GET_QQ_LOGIN_UNION_ID);
        MainHttpUtil.cancel(MainHttpConsts.LOGIN_BY_THIRD);
        MainHttpUtil.cancel(MainHttpConsts.GET_BASE_INFO);
        MainHttpUtil.cancel(MainHttpConsts.GET_LOGIN_INFO);
        if (mLoginUtil != null) {
            mLoginUtil.release();
        }
        super.onDestroy();
    }
}
